package cn._2dland.bots;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletResponse;

import cn._2dland.bots.jdo.PMFactory;
import cn._2dland.bots.jdo.models.U115Account;
import cn._2dland.gae.httpclient.HttpClient;
import cn._2dland.gae.httpclient.NameValuePair;
import cn._2dland.gae.httpclient.method.GetMethod;
import cn._2dland.gae.httpclient.method.PostMethod;

import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("unchecked")
public class U115Bot {
	private HttpClient client = null;

	private String username = null;
	private String password = null;
	private boolean bLogin = false;

	public U115Bot(String username, String password) {
		// 初始化HttpClient
		client = new HttpClient();
		client.getParams().setUserAgent("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
		client.getParams().setClientCharset("utf-8");

		bLogin = false;
		this.username = username;
		this.password = password;
	}

	public U115Bot(Long userID) {
		// 初始化HttpClient
		client = new HttpClient();
		client.getParams().setUserAgent("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
		client.getParams().setClientCharset("utf-8");

		bLogin = false;
		// 读取账户信息
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		Query q = null;
		try{
			q = pm.newQuery(U115Account.class);
			q.setFilter("id == " + userID);
			List<U115Account> accts = (List<U115Account>)q.execute();
			U115Account ua = accts.get(0);
			username = ua.getUsername();
			password = ua.getPassword();
		}
		catch (Exception e) {
			e.printStackTrace(System.err);
		}
		finally{
			if(q != null) q.closeAll();
			pm.close();
		}
	}
	
	/** 登录 */
	public boolean login() {
		if(username == null || password == null)
			return false;
		PostMethod loginPost = new PostMethod("http://passport.115.com/?action=login&goto=http%3A%2F%2Fu.115.com%2F%3Fac%3Dmy");
		try {
			loginPost.addRequestHeader("Referer", "http://u.115.com/");
			NameValuePair[] params = {
				new NameValuePair("login[account]", username),
				new NameValuePair("login[passwd]", password),
				new NameValuePair("login[time]", "on")
			};
			loginPost.addParameters(params);

			int respCode = client.executeMethod(loginPost);
			if(respCode != HttpServletResponse.SC_OK)
				throw new Exception("HTTP Error: " + respCode);

			String body = loginPost.getResponseString();
			bLogin = (body.indexOf("<title> 登录中... </title>") >= 0);
		}
		catch (Exception e) {
			bLogin = false;
			e.printStackTrace(System.err);
		}
		finally {
			loginPost.releaseConnection();
		}
		return bLogin;
	}

	/** 是否已登录 */
	public boolean isLogin() {
		return bLogin;
	}

	/**
	 * 领取空间红包。
	 * 返回0表示当日已领取；返回负值表示服务器出错，应重试。
	 */
	public int pick() {
		int picked = 0;
		GetMethod pickGet = new GetMethod("http://u.115.com/?ct=ajax&ac=pick_storage");
		try {
			pickGet.addRequestHeader("Referer", "http://u.115.com/?ct=frame&_t=" + System.currentTimeMillis());
			int respCode = client.executeMethod(pickGet);
			if(respCode != 200)
				throw new Exception("HTTP Error: " + respCode);

			String result = pickGet.getResponseString();
			if("no".equals(result)){
				picked = 0;
			}
			else{
				JSONObject jsonObj = new JSONObject(result);
				String pickStr = jsonObj.getString("picked");
				picked = Integer.parseInt(pickStr.substring(0, pickStr.length()-2));
			}
		}
		catch (Exception e) {
			picked = -1;
			e.printStackTrace(System.err);
		}
		finally {
			pickGet.releaseConnection();
		}
		return picked;
	}

	/**
	 * 文件续期
	 * 返回false表示服务器出错，应重试 
	 */
	public boolean renew(int folder) {
		boolean bOK = false;
		GetMethod renewGet = new GetMethod("http://u.115.com/?ct=ajax");
		try {
			renewGet.addRequestHeader("Referer", "http://u.115.com/");
			renewGet.addRequestHeader("Connection", "keep-alive");
			renewGet.addRequestHeader("Keep-Alive", "115");
			renewGet.addRequestHeader("X-Requested-With", "XMLHttpRequest");
			NameValuePair[] params = {
				new NameValuePair("ac", "renew_file"),
				new NameValuePair("aid", String.valueOf(folder)),
				new NameValuePair("cid", "0"),
				new NameValuePair("is_batch", "1"),
				new NameValuePair("_", String.valueOf(System.currentTimeMillis()))
			};
			renewGet.addParameters(params);
			int respCode = client.executeMethod(renewGet);
			if(respCode != HttpServletResponse.SC_OK)
				throw new Exception("HTTP Error: " + respCode);

			String result = renewGet.getResponseString();
			JSONObject jsonObj = new JSONObject(result);
			bOK = jsonObj.getBoolean("state");
		}
		catch (Exception e) {
			bOK = false;
			e.printStackTrace(System.err);
		}
		finally {
			renewGet.releaseConnection();
		}
		return bOK;
	}
}